package com.fyzk.activity.zhifu;

import android.app.Dialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatDialog;
import android.text.Html;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.alibaba.fastjson.JSON;
import com.fyzk.activity.app.App;
import com.fyzk.activity.chongzhi.RechargeActivity;
import com.fyzk.activity.lottery.recommend_order.MyBaskOrderActivity;
import com.fyzk.activity.user.xiangxi.JCOrderDetailActivity;
import com.fyzk.activity.user.xiangxi.NumLotteryOrderDetailActivity;
import com.fyzk.activity.user.xiangxi.OldFootballOrderDetailActivity;
import com.fyzk.base.BaseActivity;
import com.fyzk.bean.BetResponse;
import com.fyzk.data.AppLotteryInfos;
import com.fyzk.data.preference.MySharedPreferences;
import com.fyzk.net.Commands;
import com.fyzk.utils.AppUtil;
import com.fyzk.utils.IntentParamUtils;
import com.fyzk.utils.LogUtils;
import com.fyzk.utils.LotteryIDUtils;
import com.fyzk.view.TopTitleView;
import com.tyjc.lottery.R;

import org.json.JSONException;
import org.json.JSONObject;
import org.xutils.view.annotation.ContentView;
import org.xutils.view.annotation.ViewInject;

import java.util.ArrayList;

import http.Common.CommandUtil;
import http.StringResultBean;

/**
 * <p>
 *
 * @author Liuss
 * @mood
 * @description
 * @date 2018/8/6 17:32
 * </p>
 */
@ContentView(R.layout.activity_payment)
public class PaymentActivity extends BaseActivity {

    @ViewInject(R.id.paymentUI_titleView)
    private TopTitleView mTitleView;
    @ViewInject(R.id.paymentUI_typeImg)
    private ImageView mTypeImg;
    @ViewInject(R.id.paymentUI_typeText)
    private TextView mTypeText;
    @ViewInject(R.id.paymentUI_needPayText)
    private TextView mNeedPayText;
    @ViewInject(R.id.paymentUI_couponLy)
    private LinearLayout mCouponLy;
    @ViewInject(R.id.paymentUI_couponNumText)
    private TextView mCouponNumText;
    @ViewInject(R.id.paymentUI_payMoneyText)
    private TextView mPayMoneyText;
    @ViewInject(R.id.paymentUI_accInfoText)
    private TextView mAccInfoText;
    @ViewInject(R.id.paymentUI_payBtn)
    private Button mPayBtn;
    @ViewInject(R.id.paymentUI_rechargeBtn)
    private Button mRechargeBtn;

    private String orderId;

    private int lotteryId;          //彩票类型id
    private int phases;             //追号期数
    private boolean isMoreMoney;    //余额是否足够支付 （账户余额 - 投注金额 >= 0 ?）
    private long needMoney;         //投注金额
    private double lowMoney;        //投注差额（投注金额 - 账户余额）
    private double balance;         //账户余额
    private String betCode;
    private long amount;
    private int multiple;
    private int oneAmount;
    private String prizeOptimize;
    private String couponId;
    private String expectedPrize;
    private int recommendType;
    private int proportions;
    private int proportionType;
    private int isShowAmt;
    private int isShowMaxSP;
    private boolean isPrizeStop;
    private boolean isZhuijia;
    private long amt;
    private String memo;            //晒单宣言

    /**
     * 彩金不足提醒对话框
     */
    private AlertDialog leftMoneyLowDialog = null;
    /**
     * 是否支付对话框
     */
    private AlertDialog payDialog = null;

    private Dialog okDialog;    // 晒单成功

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        initData();
        initListener();
    }

    @Override
    protected void onResume() {
        super.onResume();
        balance = Double.parseDouble(MySharedPreferences.getInstance().getBalance());
        lowMoney = Double.valueOf(needMoney) - balance;
        mNeedPayText.setText("当前应付金额：" + needMoney + "米");
        mPayMoneyText.setText("¥    " + needMoney);
        if (lowMoney > 0) {
            mPayBtn.setVisibility(View.GONE);
            mRechargeBtn.setVisibility(View.VISIBLE);
            String infoStr = "当前余额：<font color='#fd4a4a'>" + balance + "</font>米  "
                    + "还需支付" + AppUtil.getPrice(String.valueOf(lowMoney)) + "米";
            mAccInfoText.setText(Html.fromHtml(infoStr));
        } else {
            mPayBtn.setVisibility(View.VISIBLE);
            mRechargeBtn.setVisibility(View.GONE);
            String infoStr = "当前余额：<font color='#fd4a4a'>" + balance + "</font>米";
            mAccInfoText.setText(Html.fromHtml(infoStr));
        }
    }

    private void initData() {
        lotteryId = getIntent().getIntExtra("lotteryId", 0);
        phases = getIntent().getIntExtra("phases", 0);
        isMoreMoney = getIntent().getBooleanExtra("isMoreMoney", false);
        needMoney = getIntent().getLongExtra("needMoney", 0);
        betCode = getIntent().getStringExtra("betCode");
        amount = getIntent().getLongExtra("amount", 0);
        multiple = getIntent().getIntExtra("multiple", 0);
        oneAmount = getIntent().getIntExtra("oneAmount", 0);
        prizeOptimize = getIntent().getStringExtra("prizeOptimize");
        couponId = getIntent().getStringExtra("couponId");
        expectedPrize = getIntent().getStringExtra("expectedPrize");
        recommendType = getIntent().getIntExtra("recommendType", 0);
        proportions = getIntent().getIntExtra("proportions", 0);
        proportionType = getIntent().getIntExtra("proportionType", 0);
        isPrizeStop = getIntent().getBooleanExtra("isPrizeStop", false);
        isZhuijia = getIntent().getBooleanExtra("isZhuijia", false);
        amt = getIntent().getLongExtra("amt", 0);
        isShowAmt = getIntent().getIntExtra("isShowAmt", 0);
        isShowMaxSP = getIntent().getIntExtra("isShowMaxSP", 0);
        memo = getIntent().getStringExtra("memo");

        LogUtils.e("====lotteryId====" + lotteryId);
        setLotteryTypeData();
    }

    private void setLotteryTypeData() {
        switch (lotteryId) {
            // 竞彩足球-胜平负
            case LotteryIDUtils.JZSPF_LOTTERY_ID_INT:
                mTypeImg.setImageResource(R.drawable.main_jczq);
                mTypeText.setText("竞彩足球-胜平负");
                break;
            // 竞彩足球-半全场
            case LotteryIDUtils.JZBQC_LOTTERY_ID_INT:
                mTypeImg.setImageResource(R.drawable.main_jczq);
                mTypeText.setText("竞彩足球-半全场");
                break;
            // 竞彩足球-比分
            case LotteryIDUtils.JZBF_LOTTERY_ID_INT:
                mTypeImg.setImageResource(R.drawable.main_jczq);
                mTypeText.setText("竞彩足球-比分");
                break;
            // 竞彩足球-总进球
            case LotteryIDUtils.JZZJQ_LOTTERY_ID_INT:
                mTypeImg.setImageResource(R.drawable.main_jczq);
                mTypeText.setText("竞彩足球-总进球");
                break;
            // 竞彩足球-混合投注
            case LotteryIDUtils.JZHH_LOTTERY_ID_INT:
                mTypeImg.setImageResource(R.drawable.main_jczq);
                mTypeText.setText("竞彩足球-混合投注");
                break;
            // 竞彩篮球-胜负
            case LotteryIDUtils.JLSF_LOTTERY_ID_INT:
                mTypeImg.setImageResource(R.drawable.main_jclq);
                mTypeText.setText("竞彩篮球-胜负");
                break;
            // 竞彩篮球-让分胜负
            case LotteryIDUtils.JLRSF_LOTTERY_ID_INT:
                mTypeImg.setImageResource(R.drawable.main_jclq);
                mTypeText.setText("竞彩篮球-让分胜负");
                break;
            // 竞彩篮球-胜分差
            case LotteryIDUtils.JLSFC_LOTTERY_ID_INT:
                mTypeImg.setImageResource(R.drawable.main_jclq);
                mTypeText.setText("竞彩篮球-胜分差");
                break;
            // 竞彩篮球-大小分
            case LotteryIDUtils.JLDXF_LOTTERY_ID_INT:
                mTypeImg.setImageResource(R.drawable.main_jclq);
                mTypeText.setText("竞彩篮球-大小分");
                break;
            // 竞彩篮球-混合过关
            case LotteryIDUtils.JLHH_LOTTERY_ID_INT:
                mTypeImg.setImageResource(R.drawable.main_jclq);
                mTypeText.setText("竞彩篮球-混合过关");
                break;
            // 大乐透
            case LotteryIDUtils.DLT_LOTTERY_ID_INT:
                mTypeImg.setImageResource(R.drawable.main_daletou);
                mTypeText.setText("大乐透");
                break;
            // 福彩3D
            case LotteryIDUtils.FC3D_LOTTERY_ID_INT:
                mTypeImg.setImageResource(R.drawable.main_3d);
                mTypeText.setText("福彩3D");
                break;
            // 双色球
            case LotteryIDUtils.SSQ_LOTTERY_ID_INT:
                mTypeImg.setImageResource(R.drawable.main_ssq);
                mTypeText.setText("双色球");
                break;
            // 排列三
            case LotteryIDUtils.PL3_LOTTERY_ID_INT:
                mTypeImg.setImageResource(R.drawable.main_pai3);
                mTypeText.setText("排列三");
                break;
            // 排列五
            case LotteryIDUtils.PL5_LOTTERY_ID_INT:
                mTypeImg.setImageResource(R.drawable.main_pai5);
                mTypeText.setText("排列五");
                break;
            // 七乐彩
            case LotteryIDUtils.QLC_LOTTERY_ID_INT:
                mTypeImg.setImageResource(R.drawable.main_qlc);
                mTypeText.setText("七乐彩");
                break;
            // 七星彩
            case LotteryIDUtils.QXC_LOTTERY_ID_INT:
                mTypeImg.setImageResource(R.drawable.main_qixingcai);
                mTypeText.setText("七星彩");
                break;
            // 11选5
            case LotteryIDUtils.SD11XUAN5_LOTTERY_ID_INT:
                // 11选5
            case LotteryIDUtils.GD11XUAN5_LOTTERY_ID_INT:
                mTypeImg.setImageResource(R.drawable.main_11x5xl);
                mTypeText.setText("11选5");
                break;
            // 快3
            case LotteryIDUtils.NXK3_LOTTERY_ID_INT:
            case LotteryIDUtils.ANHUIK3_LOTTERY_ID_INT:
            case LotteryIDUtils.JSK3_LOTTERY_ID_INT:
            case LotteryIDUtils.GXK3_LOTTERY_ID_INT:
            case LotteryIDUtils.JLK3_LOTTERY_ID_INT:
                mTypeImg.setImageResource(R.drawable.main_k3xl);
                mTypeText.setText("快3");
                break;
            // 快乐十分彩
            case LotteryIDUtils.KLSF_LOTTERY_ID_INT:
            case LotteryIDUtils.GDKLSF_LOTTERY_ID_INT:
                mTypeImg.setImageResource(R.drawable.main_klsfxl);
                mTypeText.setText("快乐十分彩");
                break;
        }
    }

    private void initListener() {
        mTitleView.setOnTitleClickListener(this);
        mCouponLy.setOnClickListener(this);
        mPayBtn.setOnClickListener(this);
        mRechargeBtn.setOnClickListener(this);
    }

    @Override
    public void onClick(View view) {
        super.onClick(view);
        switch (view.getId()) {
            case R.id.paymentUI_couponLy:
                break;
            case R.id.paymentUI_payBtn:
                isMoreMoney = betAble(balance, needMoney);
                if (!isMoreMoney) {
                    showRechargeDialog(needMoney, balance);
                    return;
                }

                if (phases == 1) {
                    showPayDialog();
                } else {
                    if (AppLotteryInfos.isGaoPin(lotteryId)) {
                        if (phases > 100) {
                            showToast(AppLotteryInfos.getLotteryName(lotteryId) + "最多追100期");
                        } else {
                            zhuihao();
                        }
                    } else {
                        if (phases > 30) {
                            showToast(AppLotteryInfos.getLotteryName(lotteryId) + "最多追30期");
                        } else {
                            zhuihao();
                        }
                    }
                }

                break;
            case R.id.paymentUI_rechargeBtn:
                Intent intent = new Intent(getContext(), RechargeActivity.class);
                startActivity(intent);
                break;
        }
    }

    public boolean betAble(double balance, double needMoney) {
        return balance >= needMoney;
    }

    /**
     * 支付联网——追号投注
     * betcode	string	投注内容
     * lotteryType	int	彩种
     * chaseType	int	追号类型 1:中奖停止 2:达到中奖彩金截止 3:正常截止
     * beginPhase	string	开始期
     * amt	string	单倍彩金
     * num	string	投注总期数
     * totalPrize	int	中奖总彩金 chaseType=2时使用
     * multiple	int	倍数
     * addition	int	大乐透是否追加 1是0否
     * advancedChase	string	高级追号
     */
    public void zhuihao() {
        try {
            JSONObject params = new JSONObject();
            params.put("betcode", betCode);
            params.put("lotteryType", lotteryId);
            params.put("beginPhase", getPeriod());
            if (isPrizeStop) {
                params.put("chaseType", 1);
            } else {
                params.put("chaseType", 3);
            }
            if (isZhuijia) {
                params.put("addition", 1);
            } else {
                params.put("addition", 0);
            }
            params.put("amt", amt);
            params.put("num", phases);
            params.put("multiple", multiple);
            params.put("totalPrize", "");
            httpPostJson(CommandUtil.CHASEBET, Commands.CHASEBET, params, true);

            LogUtils.e("====追号投注 params====" + params.toString());

        } catch (JSONException e) {
            e.printStackTrace();
        }
    }

    public void httpBetOrder() {
        try {
            JSONObject params = new JSONObject();
            params.put("betcode", betCode);
            params.put("lotteryType", lotteryId);
            params.put("phase", getPeriod());
            params.put("amount", amount);
            params.put("multiple", multiple);
            params.put("oneAmount", oneAmount);
            params.put("prizeOptimize", prizeOptimize);         //prizeOptimize奖金优化（优化：1；普通：0）
            params.put("codeFilter", "0");                      //codeFilter旋转过滤（过滤：1；普通：0）
            params.put("userCouponId", couponId);          //优惠劵Id，非优惠劵投注可以不写
            params.put("expectedPrize", expectedPrize);         // 预计奖金

            if (App.isBaskOrder) { // && recommendType != 1
                // 晒单投注
                params.put("way", recommendType);               // 0推荐、1不推荐、2保密
                params.put("proportions", proportions);
                params.put("proportionType", proportionType);
                params.put("isShowAmt", isShowAmt);
                params.put("isShowMaxSP", isShowMaxSP);            //是否显示此单最高赔率---0显示---1不显示
                params.put("memo", memo);
                httpPostJson(CommandUtil.USER_COMMON_BETTING, Commands.RECOMMENDEDORDERBET, params, true);
            } else {
                // 普通投注
                httpPostJson(CommandUtil.USER_COMMON_BETTING, Commands.BET, params, true);
            }

            LogUtils.e("====竞猜投注 params====" + params.toString());

        } catch (JSONException e) {
            e.printStackTrace();
        }
    }

    public String getPeriod() {
        return AppLotteryInfos.getPeriod(lotteryId);
    }

    /**
     * 显示是否支付对话框
     */
    public void showPayDialog() {
        if (payDialog == null) {
            payDialog = new AlertDialog.Builder(this).setTitle("温馨提示")
                    .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            dialog.cancel();
                            httpBetOrder();
                        }
                    }).setNegativeButton("取消", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            dialog.cancel();
                        }
                    }).create();
        }
        payDialog.setMessage("确认购买，立即支付");
        payDialog.show();
    }

    /**
     * 显示彩金不足对话框
     *
     * @param needMoney
     * @param balance
     */
    public void showRechargeDialog(double needMoney, double balance) {
        if (leftMoneyLowDialog == null) {
            leftMoneyLowDialog = new AlertDialog.Builder(this).setTitle("投注提示")
                    .setPositiveButton("去充值", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            dialog.cancel();
                            Intent intent = new Intent(getContext(), RechargeActivity.class);
                            startActivity(intent);
                        }
                    }).setNegativeButton("返回", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            dialog.cancel();
                        }
                    }).create();
        }
        leftMoneyLowDialog.setMessage("彩金不足,彩金" + balance +
                "米，需支付" + needMoney + "米，还差" +
                AppUtil.formatToYuanLXS(needMoney - balance) + "米");
        leftMoneyLowDialog.show();
    }

    @Override
    protected void onSuccess(int requestCode, StringResultBean resultBean, String result) {
        super.onSuccess(requestCode, resultBean, result);
        LogUtils.e("====result====" + result);
        switch (requestCode) {
            case CommandUtil.USER_COMMON_BETTING:
                if (App.isBaskOrder) { //&& recommendType != 1
                    showOkDialog();
                    break;
                }
            case CommandUtil.CHASEBET:
                if (resultBean.getErrorcode().equals("0")) {
                    orderId = JSON.parseObject(resultBean.getData(), BetResponse.class).getOrderid();
                    betOrderOk(orderId, "投注成功");
                } else {
                    showToast(resultBean.getMsg());
                }
                break;
        }
    }

    @Override
    protected void onFailure(int requestCode, String errorcode, String message) {
        LogUtils.e("====errorcode====" + errorcode);
        showToast(message);
    }

    private void showOkDialog() {
        View contentView = LayoutInflater.from(this).inflate(R.layout.dialog_recommend_ok, null);
        TextView btn1 = contentView.findViewById(R.id.rrok_dialog_btn1);
        TextView btn2 = contentView.findViewById(R.id.rrok_dialog_btn2);
        btn1.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                okDialog.cancel();
            }
        });
        btn2.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                okDialog.cancel();
                Intent intent = new Intent(getContext(), MyBaskOrderActivity.class);
                startActivity(intent);
            }
        });
        if (okDialog == null) {
            okDialog = new AppCompatDialog(getContext());
        }
        okDialog.setContentView(contentView);
        okDialog.setCanceledOnTouchOutside(false);
        okDialog.show();
        okDialog.setOnCancelListener(new DialogInterface.OnCancelListener() {
            @Override
            public void onCancel(DialogInterface dialog) {
                setResult(IntentParamUtils.ZHIFU_RESULT);
                finish();
            }
        });
        okDialog.setOnDismissListener(new DialogInterface.OnDismissListener() {
            @Override
            public void onDismiss(DialogInterface dialog) {
                okDialog.dismiss();
            }
        });
    }

    /**
     * 投注成功
     *
     * @param orderId
     */
    private void betOrderOk(final String orderId, String tishi) {
        MySharedPreferences.getInstance().setBetCodeBean(lotteryId, new ArrayList<>());
        new AlertDialog.Builder(getContext()).setTitle("提示").setMessage(tishi)
                .setPositiveButton("查看订单", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.cancel();
                        Intent intent;
                        if (String.valueOf(lotteryId).contains("30") || String.valueOf(lotteryId).contains("50")) {
                            intent = new Intent(getContext(), JCOrderDetailActivity.class);
                        } else if (String.valueOf(lotteryId).contains("40")) {
                            intent = new Intent(getContext(), OldFootballOrderDetailActivity.class);
                        } else {
                            intent = new Intent(getContext(), NumLotteryOrderDetailActivity.class);
                        }
                        intent.putExtra(IntentParamUtils.BETDETAILID, orderId);
                        startActivity(intent);
                        setResult(IntentParamUtils.ZHIFU_RESULT);
                        finish();
                    }
                })
                .setNegativeButton("完成", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.cancel();
                        setResult(IntentParamUtils.ZHIFU_RESULT);
                        finish();
                    }
                }).setCancelable(false).create().show();
    }

}
